package com.smh.yunpicturebackend.controller;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.smh.yunpicturebackend.config.property.OSSConfigProperties;
import com.smh.yunpicturebackend.exception.BusinessException;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.pojo.constant.FileConstant;
import com.smh.yunpicturebackend.pojo.vo.BaseResponse;
import com.smh.yunpicturebackend.utils.AliyunOSSUtils;
import com.smh.yunpicturebackend.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author shiminghui
 * @date 2025/6/19 22:38
 * @description: 文件控制器
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Resource
    private AliyunOSSUtils aliyunOSSUtils;
    @Resource
    private OSSConfigProperties ossConfigProperties;
    @Resource
    private OSS ossClient;

    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        }
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String url = null;
        File tempFile = null;
        try {
            // 创建临时文件存储
            tempFile = File.createTempFile(FileConstant.TEMP_FILE_PREFIX + IdUtil.simpleUUID(), null);
            // 将临时文件上传到OSS
            String objectName = aliyunOSSUtils.generateObjectName(originalFilename);
            url = aliyunOSSUtils.uploadFile(ossConfigProperties.getBucketName(), objectName, tempFile);
        } catch (IOException e) {
            log.error("上传文件失败:{}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        } finally {
            // 删除临时文件
            if (tempFile != null){
                tempFile.delete();
            }
        }
        log.info("上传文件成功,文件链接为:{}", url);
        return ResultUtils.success(url);
    }

    @GetMapping("/download")
    public void downloadFile(String filePath, HttpServletResponse response) {
        GetObjectRequest request = new GetObjectRequest(ossConfigProperties.getBucketName(),
                filePath);
        OSSObject object = ossClient.getObject(request);
        try (InputStream objectContent = object.getObjectContent()) {
            byte[] bytes = new byte[1024 * 1024];
            int read = 0;
            while ((read = objectContent.read(bytes)) != -1) {
                response.getOutputStream().write(bytes, 0, read);
            }
        } catch (IOException e) {
            log.error("下载文件失败:{}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载文件失败");
        }
    }

}
